<?php
require_once 'lucene/Custom_Search_Lucene_Document.php';

class SearchIndexer {
	
	protected static $_baseDirecotry;
	protected static $_indexDirctory;
	
	public static function observerTableRow($event, $row) {
		switch($event) {
			case 'post-insert':
				$doc = self::getDocument($row);
				if ($doc !== false) {
					self::_addToIndex($doc);
				}
				break;
		}
	}
	
	
	public static function getDocument($class, $row) {
		if (method_exists($class, '_getSearchIndexFields')) {
			$fields = array();
			if ($class == 'Invitation') {
				$fields = Invitation::_getSearchIndexFields($row);
				$doc = new Custom_Search_Lucene_Document($fields[Custom_Search_Lucene_Document::CLASS_NAME], $fields[Custom_Search_Lucene_Document::KEY], $fields[Custom_Search_Lucene_Document::CONTENT], $fields[Custom_Search_Lucene_Document::DESCRIPTION], $fields[Custom_Search_Lucene_Document::DATE], $fields[Custom_Search_Lucene_Document::CREATED]);
			} else if ($class == 'Custom_Friend') {
				$fields = Custom_Friend::_getSearchIndexFields($row);
				$doc = new Friend_Search_Lucene_Document($fields[Friend_Search_Lucene_Document::CLASS_NAME], $fields[Friend_Search_Lucene_Document::KEY], $fields[Friend_Search_Lucene_Document::USERNAME], $fields[Friend_Search_Lucene_Document::EMAIL]);
			}
			return $doc;
		}
		return false;
	}
	
	public static function setBaseDirectory($dir) {
		self::$_baseDirecotry = $dir;
	}
	
	public static function setIndexDirctory($subDir) {
		self::$_indexDirctory = self::$_baseDirecotry.'/'.$subDir;
	}
	
	public static function getIndexDirectory() {
		return self::$_indexDirctory;
	}
	
	public static function _addToIndex($index, $doc) {
		
		$index->addDocument($doc);
		$index->commit();
		$index->optimize();
	}
}
?>